# coding=utf-8

import tornado.web

import WrapCursor
from CommonLib import *
from database.models.Controller import Controller
from database.models.ControllerPoint import ControllerPoint
from database.models.DatabaseCommon import *


class GetControlPointInfoHandler(tornado.web.RequestHandler):

    def post(self):
        ojson = None
        r = WrapCursor.WrapCursor()
        id = None
        try:
            ojson = json.loads(self.request.body)
            id = ojson['id']
            CheckJsonKeys(ojson, 'username', 'userpass')
            CheckAuth(ojson)
        except:
            self.write(r.Error('request data error'))
            return
        sql = None
        ret = ""
        data_set = None
        col_name = None
        if id == -1:
            filter = dict()
        else:
            filter = {'id': id}

        session = Session()
        points = session.query(ControllerPoint).filter_by(**filter).all()
        jsonret = dict()
        jsonret['Code'] = 0
        jsonret['desc'] = u'成功'
        data = list()
        jsonret['data'] = data

        def GetValue(c,i):
            s=Session()
            cs = session.query(Controller).filter_by(id=c).all()
            if len(cs) == 1:
                v = int(cs[0].Value)
                v1 = v & 1 << i
                if v1 == 0:
                    return 0
                else:
                    return 1

        for i in points:
            o = dict()
            o['ControllerID'] = i.ControllerID
            o['PointIndex'] = i.PointIndex
            o['id'] = i.id
            o['name'] = i.name
            o['Value'] = GetValue(i.ControllerID,i.PointIndex -1)
            data.append(o)

        self.write(json.dumps(jsonret))